package com.sso.Login.controller;

import com.sso.Login.pojo.User;
import com.sso.Login.utils.LoginCacheUtil;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;

@Controller
@RequestMapping("/login")
public class LoginController {
    private static Set<User> dbUser;
    static {
        dbUser = new HashSet<>();
        dbUser.add(new User().setUsername("DJ").setPassword("123").setId(1));
        dbUser.add(new User().setUsername("ZS").setPassword("123").setId(2));
        dbUser.add(new User().setUsername("LS").setPassword("123").setId(3));
    }

    //登录逻辑
    @PostMapping("/doLogin")
    public String doLogin(User user, HttpSession session, HttpServletResponse response) throws IOException {
        String target = (String) session.getAttribute("target");

        Optional<User> first =
                dbUser.stream()
                        .filter(dbUser -> dbUser.getUsername().equals(user.getUsername()) && dbUser.getPassword().equals(user.getPassword()))
                        .findFirst();

        //用户登录成功，保存用户登录信息,将Token写入Cookie
        if (first.isPresent()) {
            String token = UUID.randomUUID().toString();
            Cookie cookie = new Cookie("TOKEN",token);

            cookie.setDomain("localhost");
            cookie.setPath("/");

            response.addCookie(cookie);
            LoginCacheUtil.loginUser.put(token,first.get());

        }else {
            session.setAttribute("msg","用户名或密码错误");
            return "login";
        }

        return "redirect:" + target;
    }

    @GetMapping("/info")
    public ResponseEntity<User> getUserInfo(String token){
        if (StringUtils.isEmpty(token)) {
            User user = LoginCacheUtil.loginUser.get(token);
            return ResponseEntity.ok(user);
        }else {
            return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST);
        }
    }
}
